package com.example.myapplication;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.Serializable;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener {

    EditText et_username, et_password;
    TextView tv_registered;
    Button bt_login;
    CheckBox cb_remember;
    Intent intent;
    User user;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        init_view();
        tv_registered.setOnClickListener(this);
        bt_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (et_username.getText().toString().isEmpty() || et_password.getText().toString().isEmpty()) {
                    Toast.makeText(LoginActivity.this, "用户名和密码不能为空", Toast.LENGTH_SHORT).show();
                } else {
                    if (cb_remember.isChecked()) {
                        intent = new Intent(LoginActivity.this, SuccessActivity.class);
                        intent.putExtra("user", user);
                        startActivity(intent);
                        finish();
                    } else {
                        Toast.makeText(LoginActivity.this, "请勾选记住密码", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
    }

    public void init_view() {
        et_username = findViewById(R.id.et_username);
        et_password = findViewById(R.id.et_password);
        tv_registered = findViewById(R.id.tv_registered);
        bt_login = findViewById(R.id.bt_login);
        cb_remember = findViewById(R.id.cb_remember);
    }

    @Override
    public void onClick(View v) {
        intent = new Intent(this, RegisteredActivity.class);
        startActivityForResult(intent, 50);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        user = (User) data.getSerializableExtra("user");
        et_username.setText(user.getUsername());
        et_password.setText(user.getPassword());
    }
}